<template>
  <div class="field-settings-demo">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>字段设置功能演示</span>
          <el-button type="info" @click="showFieldSelector = !showFieldSelector">
            <el-icon>
              <component :is="showFieldSelector ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
            字段设置
          </el-button>
        </div>
      </template>
      
      <!-- 字段设置面板 -->
      <transition name="field-panel">
        <div v-if="showFieldSelector" class="field-selector-panel">
          <div class="field-sorter">
            <div class="sorter-header">
              <h4>字段排序设置</h4>
              <p class="sorter-description">使用上下箭头调整字段显示顺序，勾选要显示的字段</p>
            </div>
            
            <div class="field-list-sortable">
              <div
                v-for="(field, index) in sortedFields"
                :key="field.value"
                class="field-item"
                :class="{ 'field-disabled': !selectedFields.includes(field.value) }"
              >
                <div class="field-drag-handle">
                  <span class="drag-icon">⋮⋮</span>
                </div>
                <el-checkbox
                  v-model="selectedFields"
                  :value="field.value"
                  :disabled="field.required"
                  class="field-checkbox"
                >
                  <span class="field-label">{{ field.label }}</span>
                  <span v-if="field.required" class="required-mark">*</span>
                </el-checkbox>
                <div class="field-group-tag">
                  <el-tag size="small" :type="getGroupTagType(field.group)">
                    {{ getGroupTitle(field.group) }}
                  </el-tag>
                </div>
                <div class="field-sort-controls">
                  <el-button
                    size="small"
                    :disabled="index === 0"
                    @click="moveFieldUp(index)"
                    circle
                    type="primary"
                    plain
                  >
                    ↑
                  </el-button>
                  <el-button
                    size="small"
                    :disabled="index === sortedFields.length - 1"
                    @click="moveFieldDown(index)"
                    circle
                    type="primary"
                    plain
                  >
                    ↓
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 字段设置操作按钮 -->
          <div class="field-actions">
            <el-button type="primary" @click="saveCurrentFieldSettings">
              <el-icon><Check /></el-icon>
              保存设置
            </el-button>
            <el-button type="success" @click="setAsDefaultSettings">
              <el-icon><Star /></el-icon>
              设为默认
            </el-button>
            <el-button @click="resetFieldSettings">
              <el-icon><Refresh /></el-icon>
              重置默认
            </el-button>
            <el-button type="warning" @click="clearDefaultSettings">
              <el-icon><Delete /></el-icon>
              清除默认
            </el-button>
            <el-button @click="showFieldSelector = false">
              <el-icon><Close /></el-icon>
              关闭
            </el-button>
          </div>
        </div>
      </transition>
      
      <!-- 说明文字 -->
      <div class="demo-description">
        <el-alert
          title="功能说明"
          type="info"
          :closable="false"
        >
          <ul>
            <li>字段设置功能允许用户自定义表格列的显示和排序</li>
            <li>可以勾选/取消勾选字段来控制显示</li>
            <li>使用上下箭头按钮调整字段顺序</li>
            <li>支持保存设置、设为默认、重置默认等操作</li>
            <li>必选字段（标记*）不可取消勾选</li>
          </ul>
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown, ArrowUp, Check, Star, Refresh, Delete, Close } from '@element-plus/icons-vue'
import { mockFieldConfig } from '../mock/data'

const showFieldSelector = ref(false)

// 所有字段（合并分组）
const allFields = computed(() => {
  return [
    ...mockFieldConfig.basic,
    ...mockFieldConfig.status,
    ...mockFieldConfig.time,
    ...mockFieldConfig.other
  ]
})

// 选中的字段
const selectedFields = ref([
  'id',
  'topic_name',
  'partition_id',
  'status',
  'alert_status',
  'message_timestamp',
  'last_alert_time',
  'latest_offset'
])

// 字段顺序
const fieldOrder = ref([...selectedFields.value])

// 排序后的字段列表
const sortedFields = computed(() => {
  return fieldOrder.value
    .map(value => allFields.value.find(f => f.value === value))
    .filter(Boolean)
    .map(field => ({
      ...field,
      group: getFieldGroup(field.value)
    }))
})

// 获取字段所属分组
const getFieldGroup = (value) => {
  if (mockFieldConfig.basic.find(f => f.value === value)) return 'basic'
  if (mockFieldConfig.status.find(f => f.value === value)) return 'status'
  if (mockFieldConfig.time.find(f => f.value === value)) return 'time'
  return 'other'
}

// 获取分组标题
const getGroupTitle = (group) => {
  const map = {
    basic: '基础信息',
    status: '状态信息',
    time: '时间信息',
    other: '其他信息'
  }
  return map[group] || '其他'
}

// 获取分组标签类型
const getGroupTagType = (group) => {
  const map = {
    basic: 'primary',
    status: 'success',
    time: 'warning',
    other: 'info'
  }
  return map[group] || 'info'
}

// 上移字段
const moveFieldUp = (index) => {
  if (index > 0) {
    const fields = [...fieldOrder.value]
    const [removed] = fields.splice(index, 1)
    fields.splice(index - 1, 0, removed)
    fieldOrder.value = fields
  }
}

// 下移字段
const moveFieldDown = (index) => {
  if (index < fieldOrder.value.length - 1) {
    const fields = [...fieldOrder.value]
    const [removed] = fields.splice(index, 1)
    fields.splice(index + 1, 0, removed)
    fieldOrder.value = fields
  }
}

// 保存当前设置
const saveCurrentFieldSettings = () => {
  ElMessage.success('字段设置已保存（演示模式）')
}

// 设为默认
const setAsDefaultSettings = () => {
  localStorage.setItem('field_settings_default', JSON.stringify({
    fields: selectedFields.value,
    order: fieldOrder.value
  }))
  ElMessage.success('已设为默认设置（演示模式）')
}

// 重置为默认
const resetFieldSettings = () => {
  const saved = localStorage.getItem('field_settings_default')
  if (saved) {
    const data = JSON.parse(saved)
    selectedFields.value = [...data.fields]
    fieldOrder.value = [...data.order]
    ElMessage.success('已重置为默认设置（演示模式）')
  } else {
    ElMessage.info('未找到默认设置')
  }
}

// 清除默认
const clearDefaultSettings = () => {
  localStorage.removeItem('field_settings_default')
  ElMessage.success('已清除默认设置（演示模式）')
}
</script>

<style scoped>
.field-settings-demo {
  padding: 0;
  margin-top: 20px;  /* 标签页内容区域顶部间距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.field-selector-panel {
  margin-top: 16px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.sorter-header {
  margin-bottom: 16px;
}

.sorter-header h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.sorter-description {
  margin: 0;
  color: #606266;
  font-size: 13px;
}

.field-list-sortable {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.2s;
}

.field-item:hover {
  background: #f0f2f5;
  border-color: #c0c4cc;
}

.field-item.field-disabled {
  opacity: 0.5;
}

.field-drag-handle {
  cursor: grab;
}

.drag-icon {
  color: #909399;
  font-size: 14px;
  font-weight: bold;
}

.field-checkbox {
  flex: 1;
}

.field-label {
  margin-left: 8px;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.field-group-tag {
  flex-shrink: 0;
}

.field-sort-controls {
  display: flex;
  gap: 4px;
}

.field-sort-controls .el-button {
  width: 28px;
  height: 28px;
  padding: 0;
}

.field-actions {
  display: flex;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.demo-description {
  margin-top: 20px;
}

.demo-description ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.demo-description li {
  margin-bottom: 4px;
  color: #606266;
}

/* 折叠动画 */
.field-panel-enter-active,
.field-panel-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.field-panel-enter-from,
.field-panel-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.field-panel-enter-to,
.field-panel-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 1000px;
}
</style>

